//
// Created by ZLY on 2025/5/12.
//

#include "hud_button.h"

void HUDButton::update(float dt) {
    ObjectScreen::update(dt);
    checkHover();
    checkState();
}

bool HUDButton::handleEvents(SDL_Event &event) {
    ObjectScreen::handleEvents(event);
    if (event.type == SDL_EVENT_MOUSE_BUTTON_DOWN) {
        if (event.button.button == SDL_BUTTON_LEFT) {
            if (is_hovered_) {
                is_pressed_ = true;
                game_.playSound("resources/sound/UI_button08.wav");
                return true;
            }
        }
    } else if (event.type == SDL_EVENT_MOUSE_BUTTON_UP) {
        if (event.button.button == SDL_BUTTON_LEFT) {
            is_pressed_ = false;
            if (is_hovered_) {
                is_trigger_ = true;
                return true;
            }
        }
    }
    return false;
}

void HUDButton::checkHover() {
    bool new_hover;
    auto pos = render_pos_ + sprite_normal_->getOffset();
    auto size = sprite_normal_->getSize();
    if (game_.isMouseInRect(pos, pos + size)) {
        new_hover = true;
    } else {
        new_hover = false;
    }
    if (new_hover != is_hovered_) {
        is_hovered_ = new_hover;
        if (is_hovered_ && !is_pressed_) {
            game_.playSound("resources/sound/UI_button12.wav");
        }
    }
}

void HUDButton::checkState() {
    if (!is_pressed_ && !is_hovered_) {
        sprite_normal_->setActive(true);
        sprite_hover_->setActive(false);
        sprite_pressed_->setActive(false);
    } else if (is_pressed_ && !is_hovered_) {
        sprite_normal_->setActive(false);
        sprite_hover_->setActive(false);
        sprite_pressed_->setActive(true);
    } else {
        sprite_normal_->setActive(false);
        sprite_hover_->setActive(true);
        sprite_pressed_->setActive(false);
    }
}

void HUDButton::setScale(float scale) {
    sprite_normal_->setScale(scale);
    sprite_hover_->setScale(scale);
    sprite_pressed_->setScale(scale);
}

HUDButton *HUDButton::addHUDButtonChild(Object *parent, glm::vec2 render_pos, const std::string &file_path1,
                                        const std::string &file_path2, const std::string &file_path3, float scale,
                                        Anchor anchor) {
    auto button = new HUDButton();
    button->init();
    button->setRenderPos(render_pos);
    button->sprite_normal_ = Sprite::addSpriteChild(button, file_path1, scale, anchor);
    button->sprite_hover_ = Sprite::addSpriteChild(button, file_path2, scale, anchor);
    button->sprite_pressed_ = Sprite::addSpriteChild(button, file_path3, scale, anchor);
    button->sprite_hover_->setActive(false);
    button->sprite_pressed_->setActive(false);
    if (parent) {
        parent->addChild(button);
    }
    return button;
}
